package com.example.chat_websocket.utils;

import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @Author 张云飞
 * @Date 2021/8/12 0012 13:02
 * @注释
 */
public class JWTUtils {
    //自定义秘钥
    private static final String jwtToken="22582qwewer!@$#";

    public static String createToken(String username){
        Map<String,Object> claims=new HashMap<>();
        claims.put("username",username);
        JwtBuilder jwtBuilder= Jwts.builder()
                .signWith(SignatureAlgorithm.HS256,jwtToken)//A 签发算法，秘钥为jwtToken
                .setClaims(claims)                          //B body数据，要唯一，自行设置
                .setIssuedAt(new Date())                    //设置签发时间
                .setExpiration(new Date(System.currentTimeMillis()+24*60*60*1000));
        String token=jwtBuilder.compact();
        return token;
    }

    //解析
    public static Map<String,Object> checkToken(String token){
        try {
            Jwt parse=Jwts.parser().setSigningKey(jwtToken).parse(token);
            return (Map<String,Object>) parse.getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {
        String token=JWTUtils.createToken("user");
        System.out.println(token);
        Map<String,Object> map=JWTUtils.checkToken(token);
        System.out.println(map.get("username"));
    }

}